package com.primefaces.portal.mindmap;  

import java.io.Serializable;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

import org.primefaces.event.SelectEvent;
import org.primefaces.model.mindmap.DefaultMindmapNode;
import org.primefaces.model.mindmap.MindmapNode;

import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.model.Organization;
import com.liferay.portal.model.Role;
import com.liferay.portal.model.User;
import com.liferay.portal.service.OrganizationLocalServiceUtil;
import com.liferay.portal.service.RoleLocalServiceUtil;
import com.liferay.portal.service.UserLocalServiceUtil;
import com.liferay.portal.theme.ThemeDisplay;
import com.primefaces.portal.bean.OrganizationBean;
import com.primefaces.portal.bean.UserBean;
  
@ManagedBean(name="portalMindmapBean")
@ViewScoped
public class PortalMindmapBean implements Serializable {  
	
	private static final Log _log = LogFactoryUtil.getLog(PortalMindmapBean.class);
	/**
	 * @author Azam azam@mpowerglobal.com
	 * This  is the controller class for managing all the actions to represent Organizations in the MindMap View.
	 * For any doubts or clarity please contact any time

			Mohammed Azam
			azam@mpowerglobal.com
			www.mpowerglobal.com
			+91 9844312975
	 */
	private static final long serialVersionUID = 1L;
	
	private UserBean userBean = new UserBean();
	private OrganizationBean organizationBean = new OrganizationBean();

	private boolean selectedUser = false;
	private boolean selectedOrganization = false;

	
	public OrganizationBean getOrganizationBean() {
		return organizationBean;
	}

	public void setOrganizationBean(OrganizationBean organizationBean) {
		this.organizationBean = organizationBean;
	}

	public UserBean getUserBean() {
		return userBean;
	}
	
	public void setUserBean(UserBean userBean) {
		this.userBean = userBean;
	}

	private MindmapNode root;  
      
    private MindmapNode selectedNode;  
    
	public void setRoot(MindmapNode root) {
		this.root = root;
	}
	
	public boolean getSelectedUser() {
		return selectedUser;
	}

	public void setSelectedUser(boolean selectedUser) {
		this.selectedUser = selectedUser;
	}

	public boolean getSelectedOrganization() {
		return selectedOrganization;
	}

	public void setSelectedOrganization(boolean selectedOrganization) {
		this.selectedOrganization = selectedOrganization;
	}  

	@PostConstruct
	public void init() {  
		FacesContext facesContext = FacesContext.getCurrentInstance();
		ThemeDisplay themeDisplay = (ThemeDisplay)facesContext.getExternalContext().getRequestMap().get(WebKeys.THEME_DISPLAY);
    	root = new DefaultMindmapNode(MindmapConstants.PORTAL_NAME, MindmapConstants.PORTAL_NAME, MindmapConstants.PORTAL_COLOR, false);

		if(themeDisplay.getPermissionChecker().isOmniadmin()){
			//Admin tracks all Organizations of the portal
	    	try{
	    		//Initialize all the top level organizations
	    		List<Organization> orgs = OrganizationLocalServiceUtil.getOrganizations(themeDisplay.getCompanyId(), 0);
	    		for(Organization org : orgs){
	    	        MindmapNode childOrg = new DefaultMindmapNode(org.getName() + " ("+ org.getSuborganizationsSize()  +")", org, MindmapConstants.ORGANIZATION_COLOR, true);  
		        	root.addNode(childOrg);
	    		}
	    		
	    		
	    	}catch(Exception  e){
	    		_log.error("exception caught while getting Organizations"+e.getMessage());
	    	}
	    	
		} else {
			
			//User Organizations tracking
			User user = themeDisplay.getUser();
			try{
				List<Organization> orgs = OrganizationLocalServiceUtil.getUserOrganizations(user.getUserId());
				root.addNode(new DefaultMindmapNode(user.getScreenName(), user, MindmapConstants.USER_COLOR, true));
				for(Organization org : orgs){
	    	        MindmapNode childOrg = new DefaultMindmapNode(org.getName() , org, MindmapConstants.ORGANIZATION_COLOR, false);  
		        	root.addNode(childOrg);
	    		}
			}catch(Exception  e){
	    		_log.error("exception caught while getting Organizations"+e.getMessage());
	    	}
			
		}
    }  
  
    public MindmapNode getRoot() {  
        return root;  
    }  
  
    public MindmapNode getSelectedNode() {  
        return selectedNode;  
    }  
    public void setSelectedNode(MindmapNode selectedNode) {  
        this.selectedNode = selectedNode;  
    }  
  
    public void onNodeSelect(SelectEvent event) {  
    	
    	this.setSelectedUser( false);
    	this.setSelectedOrganization(false);
    	
        MindmapNode node = (MindmapNode) event.getObject();  
        
        if(node.getChildren().isEmpty()) {
        	Object data = node.getData();
        	if(data instanceof Organization ) {
        		Organization selectedOrganization = (Organization) data;
        		try {
						List<Organization> subOrg = selectedOrganization.getSuborganizations();
						List<User> users  = UserLocalServiceUtil.getOrganizationUsers(selectedOrganization.getOrganizationId());
						
						for(User user : users){
	    	        		node.addNode(new DefaultMindmapNode(user.getScreenName(), user, MindmapConstants.USER_COLOR, true));  
	    	        	}
					
						for(Organization organization : subOrg){
							//logic to list all there suborganizations and there users
							
		        			boolean flag = false;
	
							if(organization.hasSuborganizations() || UserLocalServiceUtil.getOrganizationUsersCount(organization.getOrganizationId())  > 0) {
								flag = true;
							}
							
							node.addNode(new DefaultMindmapNode(organization.getName() + " ("+ organization.getSuborganizationsSize()  +")", organization, MindmapConstants.SUB_ORGANIZATION_COLOR,flag));
							
							 users  = UserLocalServiceUtil.getOrganizationUsers(organization.getOrganizationId());
							 
			    	        	for(User user : users){
			    	        		node.addNode(new DefaultMindmapNode(user.getScreenName(), user, MindmapConstants.USER_COLOR, true));  
			    	        	}
						}
					
					
				} catch (SystemException e) {
		    		_log.error("exception caught while getting Sub Organizations"+e.getMessage());

				}
        	}
        	
        	if(data instanceof User ) {
        		//If the user is selected then listing all there Roles
        		User selectedUser = (User) data;
        		try {
					List<Role> roles =  RoleLocalServiceUtil.getUserRoles(selectedUser.getUserId());
					for(Role role : roles){
    	        		node.addNode(new DefaultMindmapNode(role.getName() , role, MindmapConstants.ROLE_COLOR, false));  
					}
					
				} catch (SystemException e) {
		    		_log.error("exception caught while getting Roles"+e.getMessage());

				}
        		
        	}
        }  
          
    }  
      
    public void onNodeDblselect(SelectEvent event) {
    	
    	//Future we can represent the data in the more details in the popup by having the backing bean
        this.selectedNode = (MindmapNode) event.getObject();     
        
        if(selectedNode.getData() instanceof Organization) {
        	
        	this.setSelectedUser( false);
        	this.setSelectedOrganization(true);
        	Organization organization = (Organization) selectedNode.getData();
            
        	organizationBean.setOrganizationId(organization.getOrganizationId());
        	organizationBean.setOrganizationName(organization.getName());
        	organizationBean.setOrganizationType(organization.getType());

        } if(selectedNode.getData() instanceof User) {
        	
        	this.setSelectedUser( true);
        	this.setSelectedOrganization(false);
        	User user = (User) selectedNode.getData();
        	String phone = "";
			try {
				phone = user.getPhones().size()>0 ? user.getPhones().get(0).getNumber() : "No Contact Info";
			} catch (SystemException e) {
				_log.error("No contact Info");
			}
        	
			userBean.setUserId(user.getUserId());
			userBean.setUserName(user.getFullName());
			userBean.setEmailAddress(user.getEmailAddress());
			userBean.setScreenName(user.getScreenName());
			userBean.setContactNo(phone);

        }
       
    }

	
	
}  